(function () {
    var id = ID();
    var socket;
    var obj = null;

    init(connect);

    function init(callback) {
        chrome.storage.local.get(["type", "server_addr", "pwd"], function (items) {
            if (items.type == undefined) {
                chrome.storage.local.set({"type": "aes"});
            }
            if (items.server_addr == undefined) {
                chrome.storage.local.set({"server_addr": "ws://localhost:8888/ws"})
            }
            if (items.pwd == undefined) {
                chrome.storage.local.set({"pwd": ""});
            }
            callback();
        });
    }


    function connect() {
        console.log("connect")
        if (!window.WebSocket) {
            window.WebSocket = window.MozWebSocket;
        }

        if (window.WebSocket) {
            var href = null;
            chrome.tabs.query({active: true, currentWindow: true}, function (arrayOfTabs) {
                // since only one tab should be active and in the current window at once
                // the return variable should only have one entry
                var activeTab = arrayOfTabs[0];
                href = activeTab.url;

                console.log("query")
                chrome.storage.local.get("type", function (items) {
                    obj = {
                        id: id,
                        key: ID(),
                        type: items.type,
                        href: href
                    };

                    console.log(JSON.stringify(obj));
                    $('#qrcode').qrcode({width: 100, height: 100, text: JSON.stringify(obj)});
                });


            });

            chrome.storage.local.get("server_addr", function (items) {
                socket = new WebSocket(items.server_addr);

                socket.onmessage = function (event) {
                    console.log(event.data);
                    socket.close();
                };

                socket.onopen = function (event) {
                    console.log("websocket 打开了");
                    var msg = {id: id};
                    console.log(JSON.stringify(msg))
                    send(JSON.stringify(msg));
                };
                socket.onclose = function (event) {
                    console.log("websocket 关闭了");
                };
            });

        }
    }

    function send(message) {
        if (!window.WebSocket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message);
        } else {
            alert("The socket is not open.");
        }
    }

    /**
     * @return {string}
     */
    function ID() {
        // Math.random should be unique because of its seeding algorithm.
        // Convert it to base 36 (numbers + letters), and grab the first 9 characters
        // after the decimal.
        return '_' + Math.random().toString(36).substr(2, 9);
    }

    function encrypt() {
        var result = "";
        switch (localStorage.type) {
            case "aes":
                result = CryptoJS.AES.encrypt(obj.href, obj.key);
                break;
            case "des":
                result = CryptoJS.DES.encrypt(obj.href, obj.key);
                break;
            case "rabbit":
                result = CryptoJS.Rabbit.encrypt(obj.href, obj.key);
                break;
            case "rc4":
                result = CryptoJS.RC4.encrypt(obj.href, obj.key);
                break;
            case "tripledes":
                result = CryptoJS.TripleDES.encrypt(obj.href, obj.key);
                break;
        }
    }

    function decrypt(response) {
        var json = null;
        switch (localStorage.type) {
            case "aes":
                json = CryptoJS.AES.decrypt(response, obj.key).toString(CryptoJS.enc.Utf8);
                break;
            case "des":
                json = CryptoJS.DES.decrypt(response, obj.key).toString(CryptoJS.enc.Utf8);
                break;
            case "rabbit":
                json = CryptoJS.Rabbit.decrypt(response, obj.key).toString(CryptoJS.enc.Utf8);
                break;
            case "rc4":
                json = CryptoJS.RC4.decrypt(response, obj.key).toString(CryptoJS.enc.Utf8);
                break;
            case "tripledes":
                json = CryptoJS.TripleDES.decrypt(response, obj.key).toString(CryptoJS.enc.Utf8);
                break;
        }

        return json;
    }
})();